import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Chapter } from './chapter.entity';

@Injectable()
export class ReaderService {
  constructor(
    @InjectRepository(Chapter)
    private readonly chapterRepository: Repository<Chapter>,
  ) { }

  // 根据书籍 ID 获取章节列表，按顺序排列
  async getChaptersByBook(bookId: number, sort: 'ASC' | 'DESC' = 'ASC'): Promise<Chapter[]> {
    return this.chapterRepository.find({
      where: { bookId },
      order: { order: sort },
    });
  }

  // 获取单个章节
  async getChapter(id: number): Promise<Chapter> {
    return this.chapterRepository.findOneBy({ id });
  }

  // 添加章节（用于测试或管理员操作）
  async createChapter(chapterData: Partial<Chapter>): Promise<Chapter> {
    const chapter = this.chapterRepository.create(chapterData);
    return this.chapterRepository.save(chapter);
  }
}
